package web;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import command.Command;
import command.HomeCommand;
import command.LoginCommand;
import command.MyUserListCommand;
import command.NewCourseCommand;
import command.NoCommand;
import command.SaveNewUserCommand;

/**
 * The class builds a proper command from {@link javax.servlet.http.HttpServletRequest} with method 
 * {@link #getCommand(HttpServletRequest)}. 
 * <p>Is a singleton.</p>
 * @author Anton2
 *
 */

public class RequestBuilder {
	private static  RequestBuilder instance = null;
	
	/**
	 * Store all existing commands here not to construct them every time. Instantiate them in constructor {@link #RequestBuilder()}  
	 */
	private  HashMap <String,Command> commands = new HashMap<String,Command>();
	
	/**
	 * In this constructor put all servlet commands of <code>{@link Command} </code>.
	 *	
	 */
	private RequestBuilder(){
		commands.put("login", new LoginCommand());
		commands.put("home", new HomeCommand());
		commands.put("newCourse", new NewCourseCommand());
		commands.put("saveNewUser",new  SaveNewUserCommand());
		commands.put("myUserList", new MyUserListCommand());
	}
	
	/**
	 * Standard singleton method.
	 * @return the only existing instance of this class.
	 */
	public  static RequestBuilder getInstance(){
		if (instance == null){
			instance = new RequestBuilder();
		}
		return instance;
	}
	
	/**
	 * @param request should have parameter <code>command</code> , which is used to 
	 * specify a command and to create it. 
	 * @return a command of according to parameter <code>command</code> from <code>request</code>.
	 * if a <code>command</code> parameter not found or there is no proper action for the <code>command</code>
	 * returns {@link NoCommand}.
	 * 
	 */ 
	public Command getCommand(HttpServletRequest request){
		
		String action = request.getParameter("command");
		
		Command command = commands.get(action);
		
		if (command == null){
			command = new NoCommand();
		}
		return command;
		
	}
}
